<template>
  <div class="order-detail-container">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="success" :icon="Download" @click="handleExportExcel">
        导出Excel
      </el-button>
    </div>

    <el-table
        :data="state.orderData"
        v-loading="state.loading"
        style="width: 100%"
        max-height="500"
    >
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column prop="createTime" label="下单时间" width="160" />
      <el-table-column prop="goodsCount" label="购买数量" width="100" />
      <el-table-column prop="sellingPrice" label="单价" width="120">
        <template #default="scope">
          ¥{{ scope.row.sellingPrice?.toFixed(2) || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="金额" width="120">
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold">
            ¥{{ scope.row.totalPrice?.toFixed(2) || '0.00' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.orderStatus)" size="small">
            {{ getOrderStatusText(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isBill" label="开票状态" width="120">
        <template #default="scope">
          <el-tag :type="getBillTagType(scope.row.isBill)" size="small">
            {{ getBillStatusText(scope.row.isBill) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="refundStatus" label="退款状态" width="120">
        <template #default="scope">
          <el-tag
              v-if="scope.row.refundStatus === '已退款'"
              type="danger"
              size="small"
          >
            {{ scope.row.refundStatus }}
          </el-tag>
          <el-tag
              v-else-if="scope.row.refundStatus !== '未退款'"
              type="warning"
              size="small"
          >
            {{ scope.row.refundStatus }}
          </el-tag>
          <span v-else>{{ scope.row.refundStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="refundReason" label="退款原因" min-width="150" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.refundReason">{{ scope.row.refundReason }}</span>
          <span v-else style="color: #ccc">-</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next, total"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
        style="margin-top: 20px; justify-content: flex-end;"
    />
  </div>
</template>

<script setup>
import { reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import axios from '@/utils/axios'

const props = defineProps({
  goodsId: {
    type: Number,
    required: true
  },
  goodsName: {
    type: String,
    required: true
  },
  dateRange: {
    type: Array,
    default: () => []
  },
  billStatus: {
    type: String,
    default: ''
  },
  refundStatus: {
    type: String,
    default: ''
  }
})

const state = reactive({
  loading: false,
  orderData: [],
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '配货完成',
    3: '出库成功',
    4: '交易成功',
    '-1': '手动关闭',
    '-2': '超时关闭',
    '-3': '商家关闭'
  }
  return statusMap[status] || '未知'
}

// 获取订单状态标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'warning',
    3: 'success',
    4: 'success',
    '-1': 'danger',
    '-2': 'danger',
    '-3': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取开票状态文本 - 修复字符串比较问题
const getBillStatusText = (isBill) => {
  console.log('isBill value:', isBill, 'type:', typeof isBill)
  const billValue = String(isBill)
  switch (billValue) {
    case '1': return '未开票'
    case '2': return '申请中'
    case '3': return '已同意'
    case '4': return '已开票'
    default: return '未知'
  }
}

// 获取开票状态标签类型 - 修复字符串比较问题
const getBillTagType = (isBill) => {
  const billValue = String(isBill)
  switch (billValue) {
    case '1': return 'info'
    case '2': return 'warning'
    case '3': return 'primary'
    case '4': return 'success'
    default: return 'info'
  }
}

// 获取订单明细数据
const getOrderDetails = async () => {
  if (!props.goodsId || !props.goodsName) return

  state.loading = true
  try {
    const params = {
      goodsId: props.goodsId,
      goodsName: props.goodsName,  // 直接使用传入的商品名称
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      startTime: props.dateRange?.[0] || '',
      endTime: props.dateRange?.[1] || '',
      billStatus: props.billStatus,
      refundStatus: props.refundStatus
    }

    const response = await axios.get('/goods-order-details', { params })
    state.orderData = response.list || []
    state.total = response.totalCount || 0

  } catch (error) {
    console.error('获取订单明细失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    state.loading = false
  }
}

// 翻页
const changePage = (val) => {
  state.currentPage = val
  getOrderDetails()
}

// 导出Excel
const handleExportExcel = async () => {
  try {
    await ElMessageBox.confirm('确定要导出当前商品的订单明细吗？', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const params = {
      goodsId: props.goodsId,
      goodsName: props.goodsName,  // 直接使用传入的商品名称
      startTime: props.dateRange?.[0] || '',
      endTime: props.dateRange?.[1] || '',
      billStatus: props.billStatus,
      refundStatus: props.refundStatus
    }

    // 构建查询字符串
    const queryString = Object.keys(params)
        .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')

    const url = `http://172.26.200.76:28019/manage-api/v1/exportGoodsOrderDetails?${queryString}`
    console.log('导出订单明细URL:', url)

    // 新窗口打开导出
    window.open(url, '_blank')

    ElMessage.success('导出请求已发送，请稍候...')

  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出失败:', error)
      ElMessage.error('导出失败: ' + (error.message || '未知错误'))
    }
  }
}

// 监听props变化
watch(
    () => [props.goodsId,props.goodsName, props.dateRange, props.billStatus, props.refundStatus],
    () => {
      state.currentPage = 1
      getOrderDetails()
    },
    { deep: true }
)

onMounted(() => {
  getOrderDetails()
})
</script>

<style scoped>
.order-detail-container {
  max-height: 70vh;
  overflow: auto;
}

.toolbar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
